package com.example.chatroom.common.interceptor;

import com.example.chatroom.common.utils.JWTUtil;
import com.example.chatroom.common.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JWTUtil jwtUtil;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1-    令牌在请求头中
        String user_token = request.getHeader("user_token");
        log.info("请求URL：{}  token:{}",request.getRequestURI(),user_token);
        if(user_token==null){
            //拦截
            log.warn("请求头user_token=null");
            return false;
        }
        //2-    校验令牌
        Claims verify = jwtUtil.verify(user_token);
        if(verify==null){
            //说明令牌是假的
            log.warn("令牌校验失败");
            response.setStatus(401);
            return false;
        }
        //3-    判断redis黑名单中是否有令牌的标记
        String jti = verify.getId();
        if(redisUtil.hasKey("BlackToken:" + jti)){
            //1-    令牌已失效
            log.warn("令牌已失效：token{}",user_token);
            response.setStatus(401);
            return false;
        }
        log.info("令牌解析成功，放行");
        return true;
    }
}